let map
let geocoder


const createMarker = ({lng, lat, onLocation}) => {
  const icon = new AMap.Icon({
    size: new AMap.Size(26, 36),
    image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
    imageSize: new AMap.Size(26, 36),
    imageOffset: new AMap.Pixel(0, 0)
  })

  const marker = new AMap.Marker({
    icon,
    iconTheme: 'numv1',
    position: new AMap.LngLat(lng, lat),
    draggable: true,
    cursor: 'move',
    raiseOnDrag: false,
    showPositionPoint: true
  })

  //事件
  marker.on('dragend', (data) => {
    const lng = data.lnglat.lng
    const lat = data.lnglat.lat

    geocoder = new AMap.Geocoder({})
    geocoder.getAddress([lng, lat], function (status, result) {
      if (status === 'complete' && result.info === 'OK') {
        const address = result.regeocode.formattedAddress
        onLocation({
          lng, lat, address
        })
      }
    })
  })
  return marker
}

//地图创建完成
const onComplete = ({onLocation}) => (data) => {
  geocoder = new AMap.Geocoder({})
  const lng = data.position.lng
  const lat = data.position.lat
  const marker = createMarker({lng, lat, onLocation})
  map.setCenter([lng, lat])
  map.add(marker)
  const address = data.formattedAddress
  onLocation({lng, lat, address})
}

//创建地图
const createMap = ({onComplete, onError}) => {
  const AMap = window.AMap
  map = new AMap.Map('my-shop-map', {
    resizeEnable: true,
    zoom: 13,
  })

  map.plugin('AMap.Geolocation', function () {
    const geolocation = new AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
      buttonOffset: new AMap.Pixel(10, 20),
      zoomToAccuracy: true,
      buttonPosition: 'RB'
    })

    geolocation.getCurrentPosition()
    if (onComplete) AMap.event.addListener(geolocation, 'complete', onComplete)
    if (onError) AMap.event.addListener(geolocation, 'error', onError)

  })
}

//定位地址(根据地址获取坐标)
const locationAddress = (text, handler) => {
  const placeSearch = new AMap.PlaceSearch({})
  placeSearch.search(text, function (status, result) {
    // 查询成功时，result即对应匹配的POI信息
    if (result.info === 'OK') {
      handler(result)
    }
  })
}

const addOneMarker = ({lng, lat, onLocation}) => {
  map.clearMap()
  map.setCenter([lng, lat])
  const marker = createMarker({lng, lat, onLocation})
  map.add(marker)
}

export {createMap, onComplete, locationAddress, addOneMarker, map}